<template>
	<view class="" v-if="time<time2"></view>
	<view v-else style="background-color: #fff;">
		<view class="head" :style="{paddingTop:h + 5 +'px' }">
			<view class="flex align-center " @click="handlenavgate">
				<view class="button flex-c">
					<text class="text">用户端</text>
					<text class="cuIcon-triangledownfill"></text>
				</view>
				<view class="title flex-c" @click.stop="handleIM">城帮食惠</view>
			</view>
			<view class="position flex-cb">
				<view class="left" @click="localStorage">
					<text class="cuIcon-locationfill" @click.stop="got"></text>
					<text class="city">{{district?district:city?city:'重新定位'}}</text>
				</view>
				<navigator url="/pageB/index/search" class="right flex-c">
					<image src="/static/search.png" mode=""></image>
					<text class="text">请输入商品名称搜索</text>
				</navigator>
			</view>
		</view>
		<!-- 轮播图 -->
		<!-- {{imglist}} -->
		<view class="image">
			<!-- <image :src="url+item" mode="widthFix"></image> -->
			<swiper class="round-dot screen-swiper" :indicator-dots="true" :circular="true" :autoplay="true"
				interval="5000" duration="500">
				<swiper-item v-for="(item,index) in imglist" :key="index">
					<image :src="url + item" mode="widthFix"></image>
				</swiper-item>
			</swiper>
		</view>

		<view style="margin-top: 20rpx;" class="gridlist">
			<view class="" v-for="(items,indexs) in gridlist" :key="indexs">
				<view class="listitem flex justify-center" @click="handlegrid(items,indexs)">
					<image :src="items.icon" mode=""></image>
					<view class="flex-c">{{items.name}}</view>
				</view>
			</view>
		</view>
		<view class="recommend">
			<view class="title_recommend flex">
				<view class="vertical"></view>
				商品推荐
			</view>
			<view class="recommend_list flex justify-between">
				<view class="itemlist  " v-for="(item,index) in recommendlist" :key="item" @click="navigate(item)">
					<image :src="url + item.goods.main_images[0]" mode=""></image>
					<view style="display: flex;">
						<view class="text">{{item.goods.name}}</view>
						<view class="new-limit" v-if="item.goods.is_new_limit == 1">新人限购</view>
					</view>
					<view class="Price flex-cb">
						<text
							class="Price_num">原价:￥{{item.goods.sku.spec_list[0].item_list[0].price||item.goods.service.price}}</text>
						<text class="numbar">销量{{item.goods.sales}}</text>
					</view>
					<view class="MemberPrice">
						会员价:￥{{item.goods.sku.spec_list[0].item_list[0].vip_price||item.goods.service.vip_price}}</view>
					<view class="integral"
						v-if="item.goods.service.point_deduct_amount != 0&&item.goods.service.point_deduct_amount">
						{{item.goods.service.point_deduct_max_amount/(item.goods.service.point_deduct_amount/100)}}积分抵扣￥{{item.goods.sku.spec_list[0].item_list[0]['point_deduct_max_amount']||item.goods.service.point_deduct_max_amount||0}}
					</view>
					<view class="integral"
						v-if="item.goods.sku.spec_list[0].item_list[0]['100_point_deduct_amount'] != 0&&item.goods.sku.spec_list[0].item_list[0]['100_point_deduct_amount']">
						{{item.goods.sku.spec_list[0].item_list[0]['point_deduct_max_amount']/(item.goods.sku.spec_list[0].item_list[0]['100_point_deduct_amount']/100)}}积分抵扣￥{{item.goods.sku.spec_list[0].item_list[0]['point_deduct_max_amount']||item.goods.service.point_deduct_max_amount||0}}
					</view>
				</view>
			</view>

			<view class="foot">©城帮食惠版权所有</view>
		</view>
	</view>
</template>

<script>
	import QQMapWX from '@/common/qqmap-wx-jssdk.min.js'
	let qqmapsdk
	export default {
		data() {
			return {
				url: 'https://guizhouchenxun.com/uploads/',
				h: 0,
				city: '',
				district: '',
				client_id: '',
				istrue: 1,
				recommendlist: [],
				imglist: [],
				gridlist: [],
				list: [{
						icon: '/static/index/8.png',
						name: '信息发布',
						url: '/pageB/index/Delivery'
					},
					{
						icon: '/static/index/9.png',
						name: '商家入驻',
						url: '/pageC/mine/Function list/SettleIn'
					},
					{
						icon: '/static/index/10.png',
						name: '代理加盟',
						url: '/pageC/mine/Function list/agent'
					},
				],
				t: [],
				settled_fee_is_open: null, //入驻规格
				tianqi: '< iframe name="\weather_inc\" src=\"http:\/\/i.tianqi.com\/?c=code&id=1\" width=\"330\" height=\"35\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe>',
				wv: {
					width: '50rpx',
					height: '30rpx'
				},
				user: '',
				time: '',
				time2: ''
			};
		},
		onLoad(e) {
			this.getAddress()
			this.$api.index({}, false).then(res => {
				this.imglist = res.data
				// console.log(this.imglist ,'嘎嘎');
				this.$forceUpdate()

			})
			// console.log("分享人信息", e)
			this.time = Date.parse(new Date()) / 1000
			this.time2 = this.$time
			if (this.time < this.time2) {
				uni.navigateTo({
					url: '/pages/index'
				})
			}
			// getApp().watch(this.watchNews, 'hasNews')
			if (e.fx == 1) {
				getApp().globalData.direct_uid = e.id
				this.isgologin(e.id)
			}
			if (e.q) {
				const q = decodeURIComponent(e.q) // 获取到二维码原始链接内容
				let t = JSON.parse(JSON.stringify(q))
				var Request = new Object();
				Request = this.GetRequest(t);
				console.log(Request, '二维码');
				this.isgologin(Request['ttps://guizhouchenxun.com/mini/extension/?id'])
				getApp().globalData.direct_uid = Request['ttps://guizhouchenxun.com/mini/extension/?id']
			}
			console.log('走到这里了============================================');
			// this.isgologin('81')
			this.url = this.$base
			this.$api.index_9({}, false).then(res => {
				console.log(res, '菜单===');
				this.gridlist = res.data
				for (let i = 0; i < res.data.length; i++) {
					this.gridlist[i].icon = this.$base + res.data[i].icon
				}
				this.gridlist = [...this.gridlist, ...this.list]
			})
			uni.getStorage({
				key: 'height',
				success: (res) => {
					this.h = res.data
				}
			})
		},
		onShareAppMessage(res) { //转发朋友
			if (res.from === 'button') { // 来自页面内分享按钮
				// console.log(res.target)
			}
			return {
				title: '快来和我一起购物返佣金',
				path: 'pages/tabbar/index?id=' + uni.getStorageSync('user').id + '&fx=1',
			}
		},
		onShareTimeline() {
			return {
				title: '快来和我一起购物返佣金',
				path: 'pages/tabbar/index?id=' + uni.getStorageSync('user').id + '&fx=1',
				// imageUrl: 'https://cdn.uviewui.com/uview/swiper/1.jpg'
			};
		},
		onPullDownRefresh() {
			this.watchNews();
			this.recommend_good(this.district)
			setTimeout(() => {
				this.city = getApp().globalData.city
				this.district = getApp().globalData.district
			}, 500)
		},
		async onShow() {
			this.watchNews();
			this.city = getApp().globalData.city
			this.district = getApp().globalData.district
			uni.getSystemInfo({
				success: function(e) {
					setTimeout(function() {
						getApp().globalData.height = e.statusBarHeight
						let iphoneXArr = ["iPhone X", "iPhone XR", "iPhone XS MAX", "iPhone 11",
							"iPhone 11 Pro Max", "iPhone 12 min", "iPhone 13 min",
							"iPhone 12 (Por)", "iPhone 13 (Por)", "iPhone 12 Por Max",
							"iPhone 13 Por Max"
						];
						for (let i = 0; i < iphoneXArr.length; i++) {
							if (e.model == iphoneXArr[i]) {
								getApp().globalData.iphone = 80
							}
						}
					}, 50);
				}
			})

			if (uni.getStorageSync('access_token') != '') {
				if (getApp().globalData.onlogin == 0) {
					if (this.istrue) {
						this.handleIM()
					}
				}
				this.$api.user({}, true).then(res => {
					if (res.code == 200001) {
						this.user = res.data

						let query = {
							userID: res.data.id.toString(),
							userSig: uni.getStorageSync('userSig').toString()
						}
						uni.$TUIKit.login(query)
							.then(function(imResponse) {
								console.log(imResponse.data, '主页登录成功！'); // 登录成功
								if (imResponse.data.repeatLogin === true) {
									// 标识帐号已登录，本次登录操作为重复登录。v2.5.1 起支持
									console.log(imResponse.data.errorInfo);
								}
							})
							.catch(function(imError) {
								console.warn('login error:', imError); // 登录失败的相关信息
							});
					}
				})
			}

			await this.recommend_good(this.district)
			uni.setTabBarStyle({
				backgroundColor: '#fff'
			})

		},
		methods: {

			// 获取位置信息
			getAddress() {
				uni.getLocation({
					success: (res) => {
						console.log(res, 'weizhi=================');
						let lnglat = res.longitude + ',' + res.latitude
						this.$api.nearest_address({}, lnglat, 1).then(res => {
							if (res.data != null) {
								console.log("获取到了", res)
								getApp().globalData.city = res.data.city
								getApp().globalData.district = res.data.district
								this.city = res.data.city
								this.district = res.data.district
								console.log(this.city, 'this.city =====');
								console.log(this.district, 'this.district =====');
							} else {
								console.log("获取失败")
								uni.showModal({
									title: '提示',
									content: '您当前城市还未添加收货地址',
									confirmText: '去添加',
									success(res) {
										if (res.confirm) {
											console.log(res,
											'点击了确定==========================');
											uni.navigateTo({
												url: '/pageC/mine/Addaddress',
												fail(res) {
													console.log(res, '失败了：：：：');
												},
												success(res) {
													console.log(res, '成功了========');
												}
											})
										}
									},

								})
							}
						})
					},
					// fail(res) {
					// 	uni.showToast({
					// 		title: '请在手机设置中将定位打开',
					// 		icon: "none",
					// 		duration: 1000
					// 	})
					// }
				})
				uni.stopPullDownRefresh()
			},
			watchNews(e) {
				// console.log("监听到了", e, uni.getStorageSync("newsList"))
				let list = uni.getStorageSync("newsList");
				let num = 0;
				for (let i in list) {
					num = num + list[i]
				}
				// console.log("一共", num)
				// if (num != 0) {
				// 	uni.setTabBarBadge({
				// 		index: 2,
				// 		text: "" + num
				// 	})
				// } else {
				// 	uni.removeTabBarBadge({
				// 		index: 2
				// 	})
				// }
			},
			handleIM() {
				uni.closeSocket()
				uni.connectSocket({
					url: 'wss://guizhouchenxun.com:8282',
					data() {
						return {
							msg: 'Hello'
						}
					},
					// #ifdef MP
					header: {
						'content-type': 'application/json'
					},
					// #endif
					// #ifdef MP-WEIXIN
					method: 'GET',
					// #endif
					success(res) {
						console.log(res);
						// 这里是接口调用成功的回调，不是连接成功的回调，请注意
					},
					fail(err) {
						console.log(err);
						// 这里是接口调用失败的回调，不是连接失败的回调，请注意
					}
				})
				uni.onSocketOpen((res) => {
					console.log('onOpen', res);
				})
				uni.onSocketError((err) => {
					console.log('onError', err);
				})

			},
			// 是否需要跳转去登录
			isgologin(id) {
				// console.log("跳转之前id", id)
				if (uni.getStorageSync('access_token') == '') {
					if (!!uni.getStorageSync("isLogin")) {
						setTimeout(() => {
							uni.navigateTo({
								url: '/pageB/login/login?id=' + id
							})
						}, 2000)
					}
				}
			},
			GetRequest(url) { //获取二维码信息
				let theRequest = new Object();
				if (url.indexOf("?") != -1) {
					let str = url.substr(1);
					let strs = str.split("&");
					for (var i = 0; i < strs.length; i++) {
						theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
					}
				}
				return theRequest;
			},
			handlenavgate() { //商家端切换
				if (uni.getStorageSync('access_token') == '') {
					this.$utils.isgologin()
				} else {
					this.$api.merchants_settled_rule().then(res => {
						this.settled_fee_is_open = res.data.settled_fee_is_open
					})
					this.$api.merchants_info({}).then(res => {
						if (res.data == null) {
							uni.showModal({
								title: '提示',
								content: '您还未入驻商家，是否去入驻',
								success: function(res) {
									if (res.confirm) {
										uni.navigateTo({
											url: '../../pageC/mine/Function list/SettleIn'
										})
									} else if (res.cancel) {
										console.log('用户点击取消');
									}
								}
							})
							return
						}
						if (this.user.is_mch === 0) {
							uni.showModal({
								title: '提示',
								content: '您还未支付商家入驻年费，是否去支付',
								success: function(res) {
									if (res.confirm) {
										uni.navigateTo({
											url: '../../pageC/mine/Function list/SettleIn'
										})
									} else if (res.cancel) {
										console.log('用户点击取消');
									}
								}
							})
							return
						}
						console.log(res, '切换::');
						let t = new Date(res.data.settled_expiry_time.replace(/-/g, "/")).getTime() / 1000; //到期时间戳
						let newt = Date.parse(new Date()) / 1000 //当前时间戳
						if (this.settled_fee_is_open == 1 && t < newt) { //到期提示
							uni.showModal({
								title: '提示',
								content: '您的店铺入驻已到期，请前往续费',
								showCancel: 'true',
								success(res) {
									if (res.confirm) {
										uni.navigateTo({
											url: '/pageA/mine/Function list/SettleIn2'
										})
									}
								}
							})
							return
						}
						if (this.settled_fee_is_open == 0 && t < newt) {
							uni.showToast({
								title: '您的入驻已到期，请联系平台管理员续费',
								icon: 'none'
							})
							return
						}
						if (res.data.review_status == 1 && t > newt) {
							uni.navigateTo({
								url: '/pageA/index'
							})
						} else if (res.data.review_status == 0) {
							uni.showToast({
								icon: 'none',
								title: '商家审核中...'
							})
						} else {
							uni.showToast({
								icon: 'none',
								title: '商家审核未通过，请通过商家入驻审核后重试'
							})
						}
					})

				}

			},
			handlegrid(data, i) {
				if (uni.getStorageSync('access_token') == '') {
					this.$utils.isgologin()
					return
				} else {
					if (data.url) {
						if (data.name != '代理加盟') {
							uni.navigateTo({
								url: data.url
							})
						} else {
							if (this.user.is_agent == 1) {
								uni.showToast({
									title: '你已经是' + this.user.agent.city + this.user.agent.district + '代理',
									icon: 'none'
								})
								return
							} else {
								uni.navigateTo({
									url: data.url
								})
							}
						}

					} else {
						uni.navigateTo({
							url: '/pageB/index/goodFood?tab=' + i + '&id=' + data.main_id + "&name=" + data.name +
								"&cid=" + data.id
						})
					}
				}


			},
			navigate(item) {
				// console.log(item);
				if (uni.getStorageSync('access_token') == '') {
					this.$utils.isgologin()
					return
				}
				if (item.main_id == 6) {
					uni.navigateTo({
						url: '/pageB/meifa_details/meifa_details?id=' + item.id
					})
				} else {
					uni.navigateTo({
						url: '/pageB/food_details?id=' + item.id + '&mch_id=' + item.mch_id + '&index=1'
					})
				}
			},
			got() {
				uni.navigateTo({
					url: '/pageB/index/location'
				})
			},
			// 获取商品列表
			recommend_good(i) {
				// console.log(11111);
				if (i) { //区不为空
					this.$api.recommend_good({
						city: this.city,
						district: this.district,
					}).then(res => {
						this.recommendlist = res.list
						// console.log(this.recommendlist);
					})
				} else {
					this.$api.recommend_good({
						city: this.city,
						// district:this.district,	
					}).then(res => {
						this.recommendlist = res.list
						// console.log(JSON.stringify(this.recommendlist,null,2))
					})
				}
			},
			localStorage(i) { //获取城市信息
				let that = this
				if (i == 1) {
					qqmapsdk = new QQMapWX({
						key: 'IJZBZ-O6ZLO-XBFWU-SDGBT-NYCW2-CMFQF'
					});
					// 调用接口
					qqmapsdk.search({
						keyword: '美食',
						success: function(res) {
							that.city = res.data[0].ad_info.city
							that.district = res.data[0].ad_info.district
							getApp().globalData.city = that.city
							getApp().globalData.district = that.district
							// this.city = that.city
							// this.district = that.district
							that.recommend_good(that.district)
						},
						fail: function(res) {
							console.log(res);
						},
					});
				} else {
					that.got()
				}
			}
		}
	}
</script>

<style lang="scss">
	.align-center {
		padding-top: 30rpx;
	}

	.new-limit {
		font-size: 18rpx;
		letter-spacing: -1rpx;
		background-color: red;
		padding: 5rpx 10rpx;
		height: 26rpx;
		color: #fff;
		margin-top: 15rpx;
	}

	.head {
		background-color: #1CD699;

		.title {
			height: 56rpx;
			font-size: 40rpx;
			font-family: PingFang SC-Bold, PingFang SC;
			font-weight: bold;
			color: #FFFFFF;
			letter-spacing: 4rpx;
			padding-right: 176rpx;
			flex: 1;
		}

		.button {
			width: 156rpx;
			height: 60rpx;
			font-size: 28rpx;
			background: rgba(255, 255, 255, .4);
			border-radius: 30rpx;
			margin-left: 20rpx;
			color: #FFFFFF;
			position: relative;

			.cuIcon-triangledownfill {
				font-size: 44rpx;
			}

			// .text_sj{
			// 	width: 100%;
			// 	height: 60rpx;
			// 	position: absolute;
			// 	border-radius: 30rpx;
			// 	left: 0;
			// 	color: #333;
			// 	bottom: -60rpx;
			// 	background: #fff;
			// }
		}

		.position {
			padding: 28rpx 20rpx 20rpx 20rpx;

			.left {
				color: #FFFFFF;
				margin-left: 3rpx;
				font-size: 24rpx;

				.cuIcon-locationfill {
					margin-right: 10rpx;
				}

				.city {
					margin-right: 10rpx;
				}

				.centigrade {
					font-size: 22rpx;
				}
			}

			.right {
				background-color: #F5F5F5;
				width: 300rpx;
				height: 52rpx;
				border-radius: 38rpx;
				color: #999999;
				font-size: 22rpx;

				image {
					width: 22rpx;
					height: 22rpx;
				}

				.text {
					margin-left: 10rpx;
				}
			}
		}
	}

	.image {
		padding: 20rpx;
		border-radius: 10rpx;
		height: 300rpx;
		overflow: hidden;

		image {
			width: 100%;
		}
	}

	.gridlist {
		display: grid;
		grid-template-columns: repeat(5, minmax(104rpx, 1fr));
		justify-items: baseline;
		padding: 0 41rpx;
		font-size: 22rpx;
		color: #333;

		.listitem {
			width: 104rpx;
			// flex: 1;
			margin-right: rpx;
			flex-wrap: wrap;

			image {
				width: 86rpx;
				height: 86rpx;
			}

			view {
				// text-align: center;
				margin-bottom: 29rpx;
				margin-top: 13rpx;
				white-space: nowrap;

			}

		}
	}

	.recommend {
		background-color: #F0F0F0;
		padding-top: 12rpx;

		.title_recommend {
			margin-left: 26rpx;

			.vertical {
				width: 10rpx;
				height: 40rpx;
				background: #1CD699;
				border-radius: 20rpx 20rpx 20rpx 20rpx;
				margin-right: 15rpx;
			}
		}

		.recommend_list {
			padding: 27rpx 22rpx 0 22rpx;
			flex-wrap: wrap;

			.itemlist {
				width: 346rpx;
				height: 555rpx;
				background-color: #fff;
				border-radius: 15rpx;
				overflow: hidden;
				margin-bottom: 14rpx;

				view {
					margin-left: 12rpx;
				}

				image {
					width: 346rpx;
					height: 336rpx;
				}

				.text {
					// width: 305rpx;
					height: 45rpx;
					font-size: 28rpx;
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 400;
					color: #333333;
					line-height: 50rpx;
					margin-bottom: 11rpx;
					overflow: hidden;
					text-overflow: ellipsis;
				}

				.Price {
					white-space: nowrap;
					padding-right: 10rpx;

					.Price_num {
						width: 167rpx;
						font-size: 26rpx;
						margin-top: 2rpx;
					}

					.numbar {
						font-size: 22rpx;
						color: #999999;
						margin-left: 70rpx;
						white-space: nowrap;
					}
				}

				.MemberPrice {
					color: #FF2E2E;
					font-size: 30rpx;
					font-weight: bold;
					height: 42rpx;
					margin-top: 15rpx;
				}

				.integral {
					color: #FF6F10;
					margin-top: 13rpx;
					font-size: 26rpx;
				}
			}

		}

		.foot {
			color: #C6C6C6;
			margin: 55rpx auto;
			text-align: center;
			font-size: 22rpx;
		}
	}
</style>